package com.cloudwise.gproject.util;

import com.cloudwise.gproject.entity.User;
import com.cloudwise.gproject.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @ fileName:MyCustomRealm
 * @ description:
 * @ author:zhz
 * @ createTime:2021/3/18 16:22
 */
public class MyCustomRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String  loginName =  (String)authenticationToken.getPrincipal();
        //查询对象
        User user = userService.queryByLoginName(loginName);
        //对象为空说明用户名错误
        if(user==null){
            throw new AccountException();
        }
        //获取加密密码
        String password = user.getPassword();
        //获取盐值
        String salt = user.getSalt();
        return new SimpleAuthenticationInfo(user,password,
                ByteSource.Util.bytes(salt),getName());
    }
}
